package com.itboye.ihomebank.me;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.alipay.PayResult;
import com.itboye.ihomebank.alipay.SignUtils;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.BindCardsList;
import com.itboye.ihomebank.bean.PayInfo;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.qianyue.PayActivity;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.WritePassPopupWindow;
import com.itboye.ihomebank.util.WriteYanZhengMaDialog;
import com.itboye.ihomebank.util.WriteYanZhengMaDialog.OnfinishListener;

/**
 * 维修支付
 * 
 */
public class ActivityXiuLiZhiFu extends BaseOtherActivity implements Observer,
		OnfinishListener {
	TextView add_shap_title_tv;
	ImageView close_icon;

	ImageView zf_zhifubao, zf_weixin, zf_yinhangka, zf_yue;

	TextView zf_danhao, zf_money, zf_xiangmu, zf_heji, zf_zongjin, go_pay;

	Intent intent;

	String id;
	String type;
	String money;
	private boolean isZfb = true;
	private UserPresenter userPresenter;
	private String uid;
	private PayInfo payInfo;
	private boolean wx;
	private boolean yhk;
	private boolean yue;
	RelativeLayout choose_card;
	private String bankId;
	TextView bank_type, card_type, item_zhanghu_num;
	private TextView editText;
	private WritePassPopupWindow passPopupWindow;
	private EditText pass;

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.zf_zhifubao:
			choose_card.setVisibility(View.GONE);
			isZfb = true;
			wx = false;
			yue = false;
			yhk = false;
			zf_zhifubao.setBackgroundResource(R.drawable.select);
			zf_weixin.setBackgroundResource(R.drawable.unselect);
			zf_yinhangka.setBackgroundResource(R.drawable.unselect);
			zf_yue.setBackgroundResource(R.drawable.unselect);
			break;
		case R.id.zf_weixin:
			choose_card.setVisibility(View.GONE);
			isZfb = false;
			wx = true;
			yue = false;
			yhk = false;
			zf_zhifubao.setBackgroundResource(R.drawable.unselect);
			zf_weixin.setBackgroundResource(R.drawable.select);
			zf_yinhangka.setBackgroundResource(R.drawable.unselect);
			zf_yue.setBackgroundResource(R.drawable.unselect);
			break;
		case R.id.go_pay:
			uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
			if (isZfb) {// 支付宝
				userPresenter.payHouse(uid, "repair", id, "6325", "0", "", "0");
			} else if (yue) {// 余额
				passPopupWindow = new WritePassPopupWindow(this, this);
				pass = (EditText) passPopupWindow.getContentView()
						.findViewById(R.id.pass);
				passPopupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
			} else if (yhk) {// 银行卡
				if (bankId == null) {
					ByAlert.alert("请先选择要支付的银行卡");
					return;
				}
				// userPresenter.payHouse(uid, "house_rent", items, "6327", "",
				// "", "0");
			}
			break;
		case R.id.zf_yue:
			isZfb = false;
			wx = false;
			yue = true;
			yhk = false;
			choose_card.setVisibility(View.GONE);
			zf_yue.setBackgroundResource(R.drawable.select);
			zf_weixin.setBackgroundResource(R.drawable.unselect);
			zf_zhifubao.setBackgroundResource(R.drawable.unselect);
			zf_yinhangka.setBackgroundResource(R.drawable.unselect);
			break;
		case R.id.zf_yinhangka:
			wx = false;
			isZfb = false;
			yue = false;
			yhk = true;
			choose_card.setVisibility(View.VISIBLE);
			zf_yinhangka.setBackgroundResource(R.drawable.select);
			zf_weixin.setBackgroundResource(R.drawable.unselect);
			zf_zhifubao.setBackgroundResource(R.drawable.unselect);
			zf_yue.setBackgroundResource(R.drawable.unselect);
			break;
		case R.id.choose_card:
			Intent intent = new Intent(this, ActivityZhangHu.class);
			intent.putExtra("type", 0);
			startActivityForResult(intent, 101);
			break;
		case R.id.btn_ok:
			String password = pass.getText().toString();
			if (password.equals("")) {
				ByAlert.alert("请输入余额支付密码");
				return;
			}
			userPresenter.yueYanzheng(uid, password);
			passPopupWindow.dismiss();
			break;
		case R.id.btn_cancel:
			passPopupWindow.dismiss();
			break;
		default:
			break;
		}
	}

	@Override
	protected int layout_id() {
		return R.layout.activity_xiuli_zhifu;
	}

	@Override
	protected void onInitController() {

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 101 && arg1 == 102) {
			BindCardsList bindCardsList = (BindCardsList) arg2
					.getSerializableExtra("model");
			bankId = bindCardsList.getBankNo();
			bank_type.setText(bindCardsList.getBank().get(0));
			card_type.setText(bindCardsList.getBank().get(1));
			item_zhanghu_num.setText(bindCardsList.getBankNo());
		}
	}

	@SuppressLint("NewApi")
	@Override
	protected void onInit() {
		dialog = new WriteYanZhengMaDialog(this);
		add_shap_title_tv.setText("立即支付");

		intent = this.getIntent();
		if (intent != null) {
			id = intent.getStringExtra("id");
			money = intent.getStringExtra("money");
			type = intent.getStringExtra("type");

		}
		zf_danhao.setText(id);
		zf_money.setText("￥" + money);
		zf_xiangmu.setText(type);
		zf_heji.setText("￥" + money);
		zf_zongjin.setText("￥" + money);
		zf_zhifubao.setBackgroundResource(R.drawable.select);
		zf_weixin.setBackgroundResource(R.drawable.unselect);
		zf_yinhangka.setBackgroundResource(R.drawable.unselect);
		zf_yue.setBackgroundResource(R.drawable.unselect);
		userPresenter = new UserPresenter(this);
	}

	@Override
	protected void onReadIntent(Bundle bundle) {

	}

	WriteYanZhengMaDialog dialog;

	@SuppressLint("NewApi")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity.getEventType() == UserPresenter.payHouse_success) {
			payInfo = (PayInfo) entity.getData();
			if (isZfb) {
				pay(payInfo);
			} else if (yhk) {
				dialog.show(getFragmentManager(), "");
				dialog.setCancelable(false);
				userPresenter.rfPay(uid, payInfo.getCode(), bankId);
			}
			ByAlert.alert(payInfo);
		} else if (entity.getEventType() == UserPresenter.payHouse_fail) {
			ByAlert.alert(entity.getData() + "<>");
		} else if (entity.getEventType() == UserPresenter.yzyue_success) {
			userPresenter.payHouse(uid, "repair", id, "6325", "0", "", "0");
			ByAlert.alert(entity.getData());
		} else if (entity.getEventType() == UserPresenter.yzyue_fail) {
			ByAlert.alert(entity.getData());
		}
	}

	// 商户PID
	public static final String PARTNER = "2088421734415555";
	// 商户收款账号
	public static final String SELLER = "wuj@ihomebank.com";
	// 商户私钥，pkcs8格式
	// public static final String RSA_PRIVATE =
	// "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKdURORLBGPAZKLBT42KvmWmplG6aLo2alJ8Yv4tAfN8RT52Uiv1KV0KTkb7gP/8jshdPoQdSCJltcnrYEJqnfprQjTmHFwqLJTnkp7ZoVm2bTfVNdfDsCFOM/jCUYpTROuUpqjlTcwVZDiJ4J3FTFZn8i4HB01MwmoCh0pPmM0vAgMBAAECgYAEXv8tt4f10yDN357kY6t1nFTb7bKuqp08amNroGFcqvJkH1MmMtFRzOMel5NXHJHeShFIAjvQKjgFflCVa5OU3EdEuh03LjLnN65zLK0l/GYXIcqcNGXQ6hkSvEyvrZkj3kxU7xPCynJYS5Dgp43N479cfkTt1dwnW/IARsaRAQJBANR2GRg+xAqcExJmS7YStD/YqarkVAAea85rxQhdWmQlDId8+lWslSxGqWkrco3h0rzLBGM2x0FntvfIIJ3kRk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mW7Z7nfE4gUHfqIqc9umZ2C9SSpk9T76AGvAkAtEkrt8HuItXLCagyuEnstWd4rkR1UiYDUsvK4FOc11nm495rcfpHkl8rtRa17y+sIPpf9VDdWzGgwFboE0n2T";
	public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKdAjdpOu9mN96rWXvTifHNOSVXFVEOMjJ+5fbgu1iy82x1KXGkBgPGGfKEUcUl4dat+gOqVLVn8Jjgj6gyY8ODQ8pygDKcqoOrt603tF+RBnfVZObcFGO6DtiayH8DP88GYVH2KvwDwan2Ne/MXMqhxHwB/Mmpt0BZjuyjDTjH3AgMBAAECgYBeZZvqc/eoIW2AmX98nXv6JFxVsYsOmPwhhjLDyoONOoY88ORZS8T4DJy42W3bNsbLJRojzFCNcjgsBXEq7QM+JnHKQ2y+M/Jq3SxOZZnwA1j4lvFjsrsV0FYc6Ym0qRpEC1yuv/1g8NndMbZmMfk79Jt6cGQ9DImvbny3fJawuQJBANLwf9puj24bbxROTvowyMN8dPbHOlxO28oDTvD0J73T77xM09FCxInP1/QkbqYO6t3KYUfVsXFW2QMliONBKe0CQQDK+vVHhG6sRgpeoFd5xsSx270N73DUnxOGehpX/Oohbxr++5XJmLBFK5Jh4wt9BuFrm6paXugVw8IUMlYb/D7zAkBiBSwEXtf7vHfTocgFbuH8JTtc6ZtvBZ4Qs5TdVzeYeIGwqKrNVQ9rUs/xPXTFaa0uPzsRXHXGSysw0SJZKBDJAkAj3+0AAeEJo6trhA1R4ZacFMk6MEqR2be6udP0HyhGVnu/+zlDEzB8WTIbCOTb6R5oRW/7XvDH//xKU4cylQePAkEAnxCTHCB1smxydtDOx/6dNEp296YMEccJw7D9QF4zWraT4kQHankjhAfyB9/18SJlzMp8LV78IEe2xoC6oO/7Yw==";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnQI3aTrvZjfeq1l704nxzTklVxVRDjIyfuX24LtYsvNsdSlxpAYDxhnyhFHFJeHWrfoDqlS1Z/CY4I+oMmPDg0PKcoAynKqDq7etN7RfkQZ31WTm3BRjug7Ymsh/Az/PBmFR9ir8A8Gp9jXvzFzKocR8AfzJqbdAWY7sow04x9wIDAQAB";
	private static final int SDK_PAY_FLAG = 1;

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(PayInfo orderBean) {
		String innerOrderCode = "";
		String innerTotalPrice = "";
		String innerDesc = "";
		String innerBody = "";
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE)
				|| TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(this)
					.setTitle("警告")
					.setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialoginterface, int i) {
									//
									finish();
								}
							}).show();
			return;
		}
		if (orderBean != null) {
			innerOrderCode = orderBean.getCode();// 订单code
			innerBody = orderBean.getDesc();// body
			innerDesc = orderBean.getName();
			innerTotalPrice = orderBean.getTotalPrice();
			if (Double.parseDouble(innerTotalPrice) <= 0) {
				innerTotalPrice = "0.01";
			}
		}

		String orderInfo = getOrderInfo(innerOrderCode, innerDesc, innerBody,
				innerTotalPrice);

		/**
		 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		/**
		 * 完整的符合支付宝参数规范的订单信息
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(ActivityXiuLiZhiFu.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	/**
	 * create the order info. 创建订单信息 code
	 * 
	 */
	private String getOrderInfo(String subject, String title, String body,
			String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + subject + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + title + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + Double.parseDouble(price) 
				+ "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + NetPublicConstant.URL
				+ "/alipaynotify" + "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息

				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(ActivityXiuLiZhiFu.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(ActivityMyGuanJia03.REFRESH);
					sendBroadcast(intent);
					finish();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失败
					// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(ActivityXiuLiZhiFu.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(ActivityXiuLiZhiFu.this, "支付失败",
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}
			default:
				break;
			}
		}

	};
	private String code;

	@Override
	public void getEditText(String edit) {
		// TODO Auto-generated method stub
		code = edit;
		ByAlert.alert(code + "");
	}

	@SuppressLint("NewApi")
	@Override
	public void cancel() {
		// TODO Auto-generated method stub
		dialog.dismiss();
	}
}
